package com.yupi.springbootinit.common;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 反向压力线程池
 */
public class ReversePressureThreadPoolExecutor extends ThreadPoolExecutor {
    private int maxCorePoolSize;

    public ReversePressureThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
                                             TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        this.maxCorePoolSize = corePoolSize;
    }

    @Override
    public void execute(Runnable command) {
        // 检查活跃线程数是否超过核心线程数
        if (getActiveCount() >= getCorePoolSize()) {
            setCorePoolSize(getCorePoolSize() + 1); // 增加核心线程数
        }
        super.execute(command); // 执行任务
    }


    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        // 检查活跃线程数是否低于最大核心线程数，并且核心线程数大于最大核心线程数
        if (getActiveCount() <= maxCorePoolSize && getCorePoolSize() > maxCorePoolSize) {
            setCorePoolSize(getCorePoolSize() - 1); // 减少核心线程数
        }
    }
}